<template>
	<view class="publishJob">
		<view class="publishJob-content">
			<view class="publishJob-header uni-flex uni-align-center">
				<image :src="userInfoStr.avatar" mode="scaleToFill" class="publishJob-header-logo" />
				<view class="publishJob-header-title">{{userInfoStr.nikeName}}</view>
				<!-- 企业认证 -->
				<!-- <image :src="`${$ImgBaseUrl}certification.png`" mode="scaleToFill" class="publishJob-header-label" /> -->
			</view>
			<view>
				<uni-forms ref="valiForm" :modelValue="valiFormData">
					<view class="formLabel no-border uni-flex-column">
						<text>发布标题<text class="red">*</text></text>
						<uni-forms-item name="name">
							<uni-easyinput class="my-input" v-model="valiFormData.name" placeholder="请输入标题"
								placeholderStyle='font-size:28rpx;' maxlength='50' />
						</uni-forms-item>
					</view>
					<view class="formLabel no-border uni-flex-column">
						<view><text>结算方式</text><text class="red">*</text><text class="label-gray">(如200元/天)</text>
						</view>
						<uni-forms-item name="price">
							<uni-easyinput class="my-input" v-model="valiFormData.price" placeholder="请输入结算方式"
								placeholderStyle='font-size:28rpx;' />
						</uni-forms-item>
					</view>

					<view class="formLabel no-border-textarea uni-flex-column">
						<text>岗位详情<text class="red">*</text></text>
						<view class="uni-flex-item">
							<uni-forms-item name="content">
								<!-- 新增容器包裹文本框和计数器 -->
								<view class="textarea-wrapper">
									<uni-easyinput type="textarea" v-model="valiFormData.content" maxlength="5000"
										placeholder="请描述您提供兼职的具体工作内容" placeholderStyle='font-size:28rpx;' />
									<view class="counter">{{ valiFormData.content.length }}/5000</view>
								</view>
							</uni-forms-item>
						</view>
					</view>
					<view class="formLabel"><text>岗位标签</text>
						<view class="labelBox uni-flex uni-flex-wrap">
							<view class="tag-list" v-for="tag in tags" :key="tag.id">
								{{ tag.name }}
								<uni-icons type="closeempty" size="16" color="#3080ED"
									@click.stop="deleteTag(tag)"></uni-icons>
							</view>
						</view>
						<view class="addLabelBox">
							<view class="labelInputContainer uni-flex">
								<input class="greyInput" v-model="newLabel" placeholder="输入自定义标签，6个字以内" maxlength="6"
									placeholderStyle='font-size:28rpx;' />
								<view class="addLabelButton" @click="addLabel">添加标签</view>
							</view>
						</view>
						<view class="labelBox2 uni-flex uni-flex-wrap">
							<view class="tag-list" v-for="tag in defaultTagsList" :key="tag.id" @click="toggleTag(tag)">
								{{ tag.name }}
							</view>
						</view>
					</view>
				</uni-forms>
			</view>
		</view>
		<view class="publishJob-footer">
			<checkbox style="transform: scale(0.7); margin-top: -6px" @click="onCheckChange" color="#2F80ED"
				backgroundColor="#EEF5FF" borderColor="#999999" activeBackgroundColor="#EEF5FF"
				activeBorderColor="#2F80ED" iconColor="#2F80ED" />
			<view class="checkbox-label">
				<view>
					零付平台提供免费的信息发布功能，请您遵守
					<text class="blue_link">《零付-零工信息平台服务公约》</text>。
				</view>
			</view>
		</view>
		<view class="publishJob-button" @click="submit('valiForm')">免费发布</view>
	</view>
</template>

<script setup lang="ts">
	import { reactive, ref, getCurrentInstance, onMounted } from 'vue'
	import { addPartTimeJob, serviceInfo, partTimeJList, addLabelApi } from "@/api/publishDemand.js";
	import { getAreaid, getCityCode } from "@/common/util.js";
	const eventChannel = getCurrentInstance().proxy.getOpenerEventChannel()

	// 响应式数据
	const isChecked = ref(false)
	const newLabel = ref('')
	const userInfoStr = ref({})
	const loading = ref(false) // 添加加载状态

	// 表单数据
	const valiFormData = reactive({
		name: "",
		price: "",
		content: "",
		cityCode: getCityCode()
	})
	const defaultTagsList = ref([])

	// 标签数据
	const tags = ref([])

	// 方法
	const onCheckChange = () => {
		isChecked.value = !isChecked.value
	}

	// 切换默认标签的选中状态（添加/移除）
	const toggleTag = (tag) => {
		const index = tags.value.findIndex(t => t.id ? t.id === tag.id : t.name === tag.name)
		if (index > -1) {
			tags.value.splice(index, 1)
		} else {
			tags.value.push(tag)
		}
	}

	// 删除标签方法（仅通过删除按钮触发）
	const deleteTag = (tag) => {
		const index = tags.value.findIndex(t => t.id ? t.id === tag.id : t.name === tag.name)
		if (index > -1) {
			tags.value.splice(index, 1)
			uni.showToast({
				icon: "none",
				title: "标签已删除",
			});
		}
	}

	// 修改添加标签方法，调用接口
	const addLabel = async () => {
		// 输入验证
		if (!newLabel.value.trim()) {
			return uni.showToast({
				icon: "none",
				title: "请输入标签内容",
			});
		}

		if (newLabel.value.length > 6) {
			return uni.showToast({
				icon: "none",
				title: "标签不能超过6个字",
			});
		}

		// 检查是否已添加相同标签
		const hasSameTag = tags.value.some(tag => tag.name === newLabel.value.trim())
		if (hasSameTag) {
			return uni.showToast({
				icon: "none",
				title: "该标签已添加",
			});
		}

		try {
			loading.value = true
			// 调用添加标签接口，参数为name
			const res = await addLabelApi({
				name: newLabel.value.trim(),
				cityCode: getCityCode()
			})

			if (res.code === 200) {
				// 接口调用成功后添加到标签列表
				tags.value.push({
					id: res.data?.id || Date.now(), // 使用接口返回的id或时间戳作为唯一标识
					name: newLabel.value.trim()
				})
				newLabel.value = "" // 清空输入框
				uni.showToast({
					icon: "success",
					title: "标签添加成功",
				});
			} else {
				uni.showToast({
					icon: "none",
					title: res.message || "添加标签失败",
				});
			}
		} catch (error) {
			console.error("添加标签失败:", error)
			uni.showToast({
				icon: "none",
				title: "网络错误，添加失败",
			});
		} finally {
			loading.value = false
		}
	}

	const isSelected = (tag) => {
		return tags.value.some(t => t.id ? t.id === tag.id : t.name === tag.name)
	}

	const submit = () => {
		if (valiFormData.name === "" || valiFormData.name === undefined) {
			return uni.showToast({
				icon: "none",
				title: "请输入标题",
			});
		}
		if (valiFormData.price === "" || valiFormData.price === undefined) {
			return uni.showToast({
				icon: "none",
				title: "请输入结算方式",
			});
		}
		if (valiFormData.content === "" || valiFormData.content === undefined) {
			return uni.showToast({
				icon: "none",
				title: "请输入岗位详情",
			});
		}
		// 新增标签必填校验
		if (tags.value.length === 0) {
			return uni.showToast({
				icon: "none",
				title: "请至少添加1个岗位标签",
			});
		}

		// 新增标签数量上限校验（不超过5个）
		if (tags.value.length > 5) {
			return uni.showToast({
				icon: "none",
				title: "标签数量不能超过5个",
			});
		}
		if (!isChecked.value) {
			uni.showToast({
				icon: "none",
				title: "请先阅读并同意《零付-零工信息平台服务公约》",
			})
			return
		}

		try {
			const params = {
				...valiFormData,
				// 添加标签数据到提交参数
				jobLabels: tags.value.map(tag => tag.id ? tag.id : tag.name)
			}
			addPartTimeJob(params).then((res) => {
				if (res.code === 200) {
					uni.showToast({
						icon: "none",
						title: "发布成功",
					});
					eventChannel.emit('acceptDataFromPageB', {
						status: 'success'
					})
					uni.navigateBack();
				}
			});
		} catch (err) {
			console.log("err", err)
		}
	}

	// 获取默认标签列表
	const getPartTimeJList = async () => {
		try {
			const PartTimeJListRes = await partTimeJList({
				cityCode: getCityCode()
			})
			console.log('PartTimeJListRes', PartTimeJListRes);
			if (PartTimeJListRes.code === 200) {
				defaultTagsList.value = PartTimeJListRes.data
			}
		} catch (error) {
			console.error('请求失败', error);
		}
	}

	onMounted(() => {
		getPartTimeJList()
		userInfoStr.value = JSON.parse(uni.getStorageSync('user_info'));
		console.log('userInfoStr.value', userInfoStr.value);
		eventChannel.on('sendDataToPageB', (data) => {
			// 修改数据查询详情接口
			if (data.initData.id) {
				serviceInfo({ id: data.initData.id, typeId: data.initData.typeId }).then(res => {
					if (res.code === 200) {
						const serviceInfo = res.data.info;
						valiFormData.name = serviceInfo.name;
						valiFormData.content = serviceInfo.content;
						valiFormData.price = serviceInfo.price;
						// 2. 处理标签数据（核心修正）
						// 字段名从 tags 改为 labels，匹配后端返回
						const labelData = serviceInfo.labels || [];
						// 确保标签格式正确（包含 id 和 name）
						tags.value = labelData.map(label => ({
							id: label.id || label.tagId || Date.now(), // 兼容不同可能的 id 字段名
							name: label.name || label // 兼容不同可能的 name 字段名
						}));
					}
				})
			}
			console.log('收到PageA数据:', data)
		})
	})
</script>
<style lang="scss">
	.formLabel {
		.uni-forms-item {
			flex: 1;
			margin-bottom: 0rpx;
		}

		.uni-easyinput__content-textarea {
			background: #f6f6f6;
			margin: 0 !important;
			padding: 20rpx;
			height: 300rpx;
			border-radius: 10rpx;
		}
	}

	.no-border {
		.uni-forms-item__content .is-input-border {
			border: none !important;
			font-size: 28rpx;
			margin-top: 6rpx;
		}
	}

	.no-border-textarea {
		.uni-forms-item__content .is-input-border {
			border: none !important;
		}
	}
</style>

<style scoped lang="scss">
	.publishJob {
		padding: 26rpx 24rpx;
		background: #f5f5f5;
		min-height: calc(100vh - 26rpx);

		.publishJob-content {
			background: #ffffff;
			border-radius: 20rpx;
			padding: 34rpx 26rpx 41rpx 23rpx;

			.publishJob-header {
				margin-bottom: 35rpx;

				.publishJob-header-logo {
					width: 68rpx;
					height: 68rpx;
					border-radius: 50%;
					background: #fafafa;
					border: 2rpx solid #eeeeee;
					margin-right: 24rpx;
				}

				.publishJob-header-title {
					font-weight: 500;
					font-size: 32rpx;
					color: #333333;
					line-height: 45rpx;
				}

				.publishJob-header-label {
					width: 123rpx;
					height: 41rpx;
					margin-left: 22rpx;
				}
			}

			.no-border {
				border-bottom: 1px solid #e2e2e2;
				margin-bottom: 29rpx;
			}

			.formLabel {
				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #303133;
					line-height: 80rpx;
				}

				.red {
					color: #dd524d;
				}

				.label-gray {
					color: #999;
					font-size: 26rpx;
					margin-left: 5rpx;
				}
			}

			.labelInputContainer {
				// margin: 20rpx 42rpx 0 0;
				margin-top: 20rpx;

				input {
					height: 70rpx;
					// background: #f6f6f6;
					border-radius: 6rpx;
					border: 1rpx solid #E2E2E2;
					padding: 0 20rpx;
					flex: 1;
				}

				.addLabelButton {
					padding: 0 22rpx;
					height: 70rpx;
					background: #E5F0FF;
					border-radius: 6rpx;
					margin-left: 24rpx;
					font-weight: 400;
					font-size: 24rpx;
					color: #2F80ED;
					line-height: 70rpx;
				}
			}

			.labelBox {
				gap: 20rpx;

				.tag-list {
					padding: 0 19rpx;
					height: 70rpx;
					border-radius: 6rpx;
					font-weight: 400;
					font-size: 28rpx;
					line-height: 70rpx;
					display: inline-flex;
					align-items: center;
					justify-content: center;
					gap: 8rpx;
					border: 1rpx solid #2F80ED;
					color: #2F80ED;
				}
			}

			.labelBox2 {
				gap: 33rpx;
				margin-top: 20rpx;

				.tag-list--selecte {
					background: #e5f0ff;
					color: #2f80ed;
				}

				.tag-list {
					padding: 0 19rpx;
					height: 70rpx;
					background: #f1f1f1;
					border-radius: 6rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
					line-height: 70rpx;
				}
			}
		}

		.publishJob-footer {
			margin: 42rpx 0 86rpx;
			display: flex;

			.checkbox-label {
				margin-left: 16rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
				line-height: 40rpx;

				.blue_link {
					color: #2f80ed;
				}
			}
		}

		.publishJob-button {
			width: 86%;
			height: 88rpx;
			background: #2f80ed;
			border-radius: 44rpx;
			text-align: center;
			font-weight: 600;
			font-size: 30rpx;
			color: #ffffff;
			line-height: 88rpx;
			margin: 0 auto;
		}
	}

	// 文本框容器样式
	.textarea-wrapper {
		position: relative;
		width: 100%;
	}

	// 调整文本框内边距，避免文字被计数器遮挡
	::v-deep .uni-easyinput[type="textarea"] .uni-easyinput__content {
		padding-bottom: 40rpx !important;
		min-height: 200rpx;
	}

	.counter {
		position: absolute;
		right: 20rpx;
		bottom: 10rpx;
		text-align: right;
		font-size: 12px;
		color: #999;
		pointer-events: none;
	}

	::v-deep .uni-easyinput__content-input {
		padding-left: 0rpx !important;
	}
</style>